package zheezes.protocol.impl.gd;

import java.util.ArrayList;
import java.util.List;

public class Ctrl81Frame extends GdFrame {
	private byte tnm[] = new byte[8];
	private List<DataItem> dis = new ArrayList<DataItem>();

	public Ctrl81Frame() {
		ctrl = (byte) 0x81;
	}
	
	public Ctrl81Frame(byte[] buf) {
		this(buf, 0);
	}
	
	public Ctrl81Frame(byte[] buf, int offset) {
		this();
		setData(buf, offset, buf.length);
	}
	
	@Override
	public int sizeOfData() {
		int size = tnm.length;
		for (DataItem di : dis) {
			size += di.getDataLength();
		}
		return size;
	}

	@Override
	public int getData(byte[] buf, int offset) {
		int idx = offset;
		byte[] db = null;
		System.arraycopy(tnm, 0, buf, idx, tnm.length);
		idx += 8;
		for (DataItem di : dis) {
			db = di.getBytes();
			System.arraycopy(db, 0, buf, idx, db.length);
			idx += db.length;
		}
		return idx - offset;
	}

	@Override
	public int setData(byte[] buf, int offset, int max) {
		int idx = offset;
		DataItem item = null;

		System.arraycopy(buf, 0, tnm, 0, tnm.length);
		idx += tnm.length;
		dis.clear();
		while (idx < max) {
			item = new DataItem(buf, idx);
			dis.add(item);
			idx += item.length();
		}
		return 0;
	}

	public DataItem[] getDataItems() {
		return dis.toArray(new DataItem[0]);
	}
}
